package com.atguigu.realtime.util;

import com.atguigu.realtime.annotation.NotSink;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/2/9 10:22
 */
public class AtguiguUtil {
    public static <T> List<T> toList(Iterable<T> it) {
        ArrayList<T> list = new ArrayList<>();
        for (T t : it) {
            list.add(t);
            
        }
        return list;
    }
    
    public static Long toTs(String time, String... timeFormat) {
        String f = "yyyy-MM-dd HH:mm:ss";
        if (timeFormat.length == 1) {
            f = timeFormat[0];
        }
        
        try {
            return new SimpleDateFormat(f).parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static String toDateTime(long ts, String... timeFormat) {
        String f = "yyyy-MM-dd HH:mm:ss";
        if (timeFormat.length == 1) {
            f = timeFormat[0];
        }
        return new SimpleDateFormat(f).format(ts);
    }
    
    // 返回指定的类的所有属性用逗号拼起来的字符串
    // stt,edt,vr,...  TODO
    public static <T> String getFieldsString(Class<T> tClass) {
        Field[] fields = tClass.getDeclaredFields();
        
        String result = "";
        for (Field field : fields) {
            // 如果有notSink, 则不需要拼接到字符串
            NotSink notSink = field.getAnnotation(NotSink.class);
            if (notSink == null) {
                result += field.getName() + ",";
            }
            
        }
        // a,b,c,   最后多一个逗号
        return result.substring(0, result.length() - 1);
    }
    
    public static void main(String[] args) {
        //        System.out.println(getFieldsString(ProductStats.class));
        System.out.println(split("我是中国人"));
    }
    
    public static Set<String> split(String kw) {
        
        Set<String> words = new HashSet<>();
        // 字符串 -> Reader
        // 内存流
        StringReader reader = new StringReader(kw);
        IKSegmenter seg = new IKSegmenter(reader, true);
        Lexeme next = null;
        try {
            next = seg.next();
            while (next != null) {
                String word = next.getLexemeText();
                words.add(word);
                next = seg.next();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return words;
    }
    
}
